package com.distribute.application.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.distribute.application.api.utils.WeiXinAccessTokenUtil;
import com.distribute.framework.core.web.helper.Utils;

public class WechatMouldUtil {
	private static final Logger logger = Logger.getLogger(WechatMouldUtil.class);
	private static final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
    /**
     * 
     * @param accessToken
     * @param formId
     * @param templateId
     * @param openId
     * @param data
     * @return
     */
	public String sendWechatmsgToUser(String formId,String templateId,String openId, Map<String, Object> data){
		 WeiXinAccessTokenUtil weiXinAccessTokenUtil=new WeiXinAccessTokenUtil();
	    	String accessToken=weiXinAccessTokenUtil.getWeChatAccessTokens();
		String url = TEMPLATE_URL.replace("ACCESS_TOKEN", accessToken);
        JSONObject json = new JSONObject();
            json.put("touser", openId);
            json.put("template_id",templateId);
            json.put("form_id",formId);
            json.put("data", data);
        String result = Utils.doPost(url, json.toString());
            JSONObject resultJson = JSON.parseObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){//如果为errmsg为ok，则代表发送成功。
            	logger.error("发送失败");
                return "error";
            }
        return "success";
    }
}